import os
from typing import Annotated

import httpx
from langchain_core.tools import tool


@tool
def nearby(
    location: Annotated[str, "中心点坐标，以“,”分割,经度在前,纬度在后,如117.500244,40.417801"],
    city_code: Annotated[str, "城市编码"],
    types: Annotated[
        str,
        """查询POI类型。多个类型用“|”分割。如果查询住宿,只能填写以下类型:“宾馆酒店”“旅馆招待所”。如果查询餐饮,只能填写
        以下类型:“中餐厅”“外国餐厅”“快餐厅”。关键字和POI类型二者至少填写一个。""",
    ] = "",
    keyword: Annotated[
        str,
        """要搜索的关键字。除非用户有特别指定具体的地点名称时才填写,如“星巴克”“希尔顿”等,否则不要填写!一次只能搜索一个
        关键字。关键字和POI类型二者至少填写一个。""",
    ] = "",
    radius: Annotated[int, "查询半径，单位米。"] = 5000,
    offset: Annotated[int, "每页搜索结果数目。"] = 20,
    page: Annotated[int, "当前页数。"] = 1,
):
    """周边搜索工具。根据中心点坐标和关键字或POI类型搜索周边POI。返回结果中,距离的单位都是米,费用的单位都是元。"""
    key = os.getenv("AMAP_API_KEY")
    url = "https://restapi.amap.com/v3/place/around"
    request_params = {
        "key": key,
        "location": location,
        "city": city_code,
        "types": types,
        "keyword": keyword,
        "radius": radius,
        "offset": offset,
        "page": page,
    }

    response = httpx.get(url, params=request_params).json()

    result = {"center": location, "suggest_count": response["count"], "pois": []}

    for poi in response["pois"]:
        result["pois"].append(
            {
                "name": poi["name"],
                "type": poi["type"],
                "address": poi["address"],
                "distance": poi["distance"],
                "location": poi["location"],
                "rating": poi["biz_ext"]["rating"] if "biz_ext" in poi else "not available",
                "cost": poi["biz_ext"]["cost"] if "biz_ext" in poi else "not available",
            }
        )

    return result


if __name__ == "__main__":
    from dotenv import find_dotenv, load_dotenv

    _ = load_dotenv(find_dotenv())
    a = nearby.invoke(
        {
            "location": "113.129362,29.371356",
            "city": "0730",
            # "keyword": "酒店",
            "types": "旅馆招待所|中餐厅",
        }
    )
    print(a)
